package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.comm.SessionInfo;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.*;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import com.mchange.v2.log.MLogger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
    * @ClassName: WmsGoodsService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author JaneLiu
    * @Date Wed Sep 06 17:06:56 CST 2017
    */

    @Service
    public class WmsGoodsService extends BaseService<WmsGoodsMapper,WmsGoods> {

        @Autowired
        private SysDictionaryService sysDictionaryService;
        @Autowired
        private WmsPackingService wmsPackingService;
        //供应商优先级表
        @Autowired
         private WmsGoodsSuppliersService wmsGoodsSuppliersService;
        //配件表
        @Autowired
        private WmsGoodsAccessoriesService wmsGoodsAccessoriesService;
        //主包装库位表
        @Autowired
        private WmsOneLevelPickingLocationMapper wmsOneLevelPickingLocationMapper;
        //内包装库位表
        @Autowired
        private WmsTwoLevelPickingLocationMapper wmsTwoLevelPickingLocationMapper;
        //箱包装库位表
        @Autowired
        private WmsThreeLevelPickingLocationMapper wmsThreeLevelPickingLocationMapper;
        //货品库位组表
        @Autowired
        private WmsGoodsLocationMapper wmsGoodsLocationMapper;
        //库存表
        @Autowired
        private WmsStockMapper wmsStockMapper;
        //货品物料清单
        @Autowired
        private WmsGoodsBomMapper wmsGoodsBomMapper;


    /**
    * 插入一条记录
    * @param map 实体对象baseSelectByGoodsEdit
    * @return int
    */

    @BaseServiceDescribe(moduleName = "货品管理",btnName = "添加货品")
    @Transactional
         public void insertByProcedure(Map<String,Object> map,String ckid,String sshzid)throws ServiceException {
             //生成新增货品Id
             map.put("id", UUIDUtils.uuid());
             //处理map添加供应商优先级
             int yxjStatus=0;//用来判断是否优先级添加成功 0 否 1是
             if(map.containsKey("gys")){
             List<Map<String,Object>>   array= JSONArray.fromObject(map.get("gys"));
             //加入仓库ID
             for(Map<String,Object> map1:array){ map1.put("ckid",ckid); }
             if(array.size()>0){
                 yxjStatus = wmsGoodsSuppliersService.baseInsert(array,map.get("id").toString());
             }else{
                 throw new RuntimeException("货品未绑定供应商，请绑定供应商");
             }
             }else{
                throw new RuntimeException("货品未绑定供应商，请绑定供应商");
             }
             //处理map添加配件信息
             int pjStatus=0;//添加配件是否成功0 否 1是
             if(yxjStatus>0){
                 map.remove("gys");
                 if(map.containsKey("pj")){
                     WmsGoodsAccessories accessories=new WmsGoodsAccessories();
                     List<Map<String,Object>> array= JSONArray.fromObject(map.get("pj"));
                     for(Map<String,Object> map2:array){ map2.put("ckid",ckid); }
                     if(array.size()>0){
                         //新增多条内容
                         pjStatus=wmsGoodsAccessoriesService.baseInsertByMap(array,map.get("id").toString());
                         }else {
                         //没有新增货品配件信息的时候继续往下走 改变状态
                         pjStatus=1;
                     }
                     }else{
                     //防止没有Key，remove报错
                     map.put("pj","");
                     //没有新增货品配件信息的时候继续往下走 改变状态
                     pjStatus=1;
                 }
             }
             //给货品绑定包装
             int packingStatus=0;//绑定包装是否成功0 否 1是
             if(pjStatus>0){
                 //删除配件信息
                 map.remove("pj");
                 if(map.containsKey("bzid")){
                     WmsPacking packing=new WmsPacking();
                     packing.setId(map.get("bzid").toString());
                     packing.setFphpid(map.get("id").toString());
                        packingStatus=wmsPackingService.baseUpdateByPrimaryKeySelective(packing);
                 }
             }
             int hhStatus=0;//记录新增货品是否成功 0失败 1成功
             if(packingStatus==1) {
                 //新增货品
                 WmsGoods goods = new WmsGoods();
                goods.setId(map.get("id").toString());
                 if (map.containsKey("bh")) goods.setBh(map.get("bh").toString());
                 if (map.containsKey("mc")) goods.setMc(map.get("mc").toString());
                 if (map.containsKey("zlid")) goods.setZlid(map.get("zlid").toString());
                 if (map.containsKey("tm")) goods.setTm(map.get("tm").toString());
                 if (map.containsKey("bzid")) goods.setBzid(map.get("bzid").toString());
                 if (map.containsKey("bkxs")) goods.setBkxs(map.get("bkxs").toString());
                 if (map.containsKey("cjsn")) goods.setCjsn(map.get("cjsn").toString());
                 if (map.containsKey("sfyx")) goods.setSfyx(map.get("sfyx").toString());
                 if (map.containsKey("zhhp")) goods.setZhhp(map.get("zhhp").toString());
                 if (map.containsKey("kczdl")) goods.setKczdl(map.get("kczdl").toString());
                 if (map.containsKey("kczxl")) goods.setKczxl(map.get("kczxl").toString());
                 if (map.containsKey("yxq")){ goods.setYxq(map.get("yxq").toString());}else{goods.setYxq("");};
                 if (map.containsKey("zqlx")) {goods.setZqlx(map.get("zqlx").toString());}else{goods.setZqlx("");}
                 if (map.containsKey("yxqkz")){ goods.setYxqkz(map.get("yxqkz").toString());}else{goods.setYxqkz("");}
                 if (map.containsKey("sxqyj")){ goods.setSxqyj(map.get("sxqyj").toString());}else{goods.setSxqyj("");}
                 if (map.containsKey("jhwzlx")) goods.setJhwzlx(map.get("jhwzlx").toString());
                 if (map.containsKey("jhwnlx")) goods.setJhwnlx(map.get("jhwnlx").toString());
                 if (map.containsKey("jhxnlx")) goods.setJhxnlx(map.get("jhxnlx").toString());
                 if (map.containsKey("jhtnlx")) goods.setJhtnlx(map.get("jhtnlx").toString());
                 if (map.containsKey("bhsx")) goods.setBhsx(map.get("bhsx").toString());
                 if (map.containsKey("bhdw")) goods.setBhdw(map.get("bhdw").toString());
                 if(map.containsKey("qzfs")) goods.setQzfs(map.get("qzfs").toString());
                 if (map.containsKey("ccqbh")) goods.setCcqbh(map.get("ccqbh").toString());
                 if (map.containsKey("xjhwbh")) goods.setXjhwbh(map.get("xjhwbh").toString());
                 if(map.containsKey("zjgzid")){ goods.setZjgzid(map.get("zjgzid").toString());}else {goods.setZjgzid("0");}
                 if(map.containsKey("bom")){goods.setBom(map.get("bom").toString());}else{goods.setBom("0");}
                 if(map.containsKey("nc")){goods.setNc(map.get("nc").toString());}else{goods.setNc("");}
                 if(map.containsKey("gg")){goods.setGg(map.get("gg").toString());}else{goods.setGg("");}
                 goods.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                 goods.setCkid(ckid);
                 hhStatus = dao.baseInsertSelective(goods);
             }
             int oneStatus=0;//判断主单位库位是否添加成功
            if(hhStatus>0){
                if(map.containsKey("jhwzlx")){
                    WmsOneLevelPickingLocation oneLocation=new WmsOneLevelPickingLocation();
                    oneLocation.setId(UUIDUtils.uuid());
                    if("0".equals(map.get("jhwzlx").toString())){
                        if(map.containsKey("zkwid")){oneLocation.setKwid(map.get("zkwid").toString());}else {oneLocation.setKwid("");}
                    }else{
                        if(map.containsKey("zkwid")){oneLocation.setKwid(map.get("zkwid").toString());}else{
                            throw new RuntimeException("库位类型不是存储库位必须选择库位");
                        }
                    }
                    if(map.containsKey("id"))oneLocation.setSshpid(map.get("id").toString());
                    oneLocation.setKwlx(map.get("jhwzlx").toString());
                    oneLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    oneLocation.setCkid(ckid);
                    oneStatus=wmsOneLevelPickingLocationMapper.baseInsert(oneLocation);
                }else{
                    //未绑定主单位库位不添加继续下行
                    oneStatus=1;
                }
            }
            int twoStatus=0;//判断内包装库位是否添加成功
            if(oneStatus>0){
                map.put("nid",UUIDUtils.uuid());
                if(map.containsKey("jhwnlx")){
                    WmsTwoLevelPickingLocation twoLocation=new WmsTwoLevelPickingLocation();
                    twoLocation.setId(UUIDUtils.uuid());
                    if("0".equals(map.get("jhwnlx").toString())){
                        if(map.containsKey("nkwid")){twoLocation.setKwid(map.get("nkwid").toString());}else {twoLocation.setKwid("");}
                    }else{
                        if(map.containsKey("nkwid")){twoLocation.setKwid(map.get("nkwid").toString());}else {
                            throw new RuntimeException("库位类型不是存储库位必须选择库位");
                        }
                    }
                    if(map.containsKey("id"))twoLocation.setSshpid(map.get("id").toString());
                    twoLocation.setKwlx(map.get("jhwnlx").toString());
                    twoLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    twoLocation.setCkid(ckid);
                  twoStatus=wmsTwoLevelPickingLocationMapper.baseInsert(twoLocation);
                }else{
                    //未绑定内包装库位不添加继续下行
                    twoStatus=1;
                }
            }
            int threeStatus=0;//判断箱单位库位是否添加成功
            if(twoStatus>0){
                map.put("xid",UUIDUtils.uuid());
                if(map.containsKey("jhxnlx")){
                    WmsThreeLevelPickingLocation threeLocation=new WmsThreeLevelPickingLocation();
                    threeLocation.setId(UUIDUtils.uuid());
                    if("0".equals(map.get("jhxnlx").toString())){
                        if(map.containsKey("xkwid")){threeLocation.setKwid(map.get("xkwid").toString());}else {threeLocation.setKwid("");}
                    }else{
                        if(map.containsKey("xkwid")){threeLocation.setKwid(map.get("xkwid").toString());}else{
                            throw new RuntimeException("库位类型不是存储库位必须选择库位");
                        }
                    }
                    if(map.containsKey("id"))threeLocation.setSshpid(map.get("id").toString());
                    threeLocation.setKwlx(map.get("jhxnlx").toString());
                    threeLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                    threeLocation.setCkid(ckid);
                    threeStatus=wmsThreeLevelPickingLocationMapper.baseInsert(threeLocation);
                }
            }
         }


   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象

    * @return int
    */
    public Integer baseInsertSelective( WmsGoods entity ){
         return dao.baseInsertSelective( entity );
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键

    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id ){
         return dao.baseDeleteByPrimaryKey( id );
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsGoods>
    */
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "分页查询货品")
    public Page<WmsGoods> baseSelectPage(WmsGoods entity)throws ServiceException{
        PageHelper.startPage(entity.getPage(),entity.getRows());
        try {
            Page<WmsGoods> list = (Page<WmsGoods>) dao.baseSelectPage(entity);
            for (WmsGoods goods : list) {
                //把状态码转换成文字显示
                String value = "";
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_zhhp.toString(), goods.getZhhp());
                goods.setShow_zhhp(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_bkxs.toString(), goods.getBkxs());
                goods.setShow_bkxs(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_cjsn.toString(), goods.getCjsn());
                goods.setShow_cjsn(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_sfyx.toString(), goods.getSfyx());
                goods.setShow_sfyx(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_bhdw.toString(), goods.getBhdw());
                goods.setShow_bhdw(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_ccqbh.toString(), goods.getCcqbh());
                goods.setShow_ccqbh(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_jhtnlx.toString(), goods.getJhtnlx());
                goods.setShow_jhtnlx(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_jhwnlx.toString(), goods.getJhwnlx());
                goods.setShow_jhwnlx(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_jhwzlx.toString(), goods.getJhwzlx());
                goods.setShow_jhwzlx(value);
                value = sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_jhxnlx.toString(), goods.getJhxnlx());
                goods.setShow_jhxnlx(value);
                value=sysDictionaryService.getTypeName(DictionaryInfo.wms_goods_bom.toString(),goods.getBom());
                goods.setShow_bom(value);
            }
            return list;
        }catch (Exception e){
            throw new ServiceException("查询货品信息失败",e);
        }
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsGoods
    */
    public WmsGoods baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsGoods> idList){
         return dao.baseSelectBathPrimaryKeys( idList);
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
   @BaseServiceDescribe(moduleName = "货品管理",btnName = "修改货品")
    public void baseUpdateByPrimaryKeySelective ( WmsGoods entity)throws ServiceException{
       try {
            dao.baseUpdateByPrimaryKeySelective( entity);
       }catch (Exception e){
           throw new ServiceException("修改货品信息失败",e);
       }
    }
    /**
     *修改货品管理新增 （匹配有值的字段）
     * @param map edit参数
     * @return int
     */
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "修改货品")
    @Transactional
    public void editByProcedure( Map<String,Object> map,String ckid,String sshzid)throws ServiceException{
        //处理map更新供应商优先级
        if(map.containsKey("gys")){
            List<Map<String,Object>>   array= JSONArray.fromObject(map.get("gys"));
            for(Map<String,Object> map1:array){map1.put("ckid",ckid);}
            if(array.size()>0){
                //删除原有供应商后添加进去新编辑的供应商
               int del= wmsGoodsSuppliersService.baseDeleteBySshpid(map.get("id").toString());
             if(del>0){
                 wmsGoodsSuppliersService.baseInsert(array,map.get("id").toString());
             }
            }else{
                throw new RuntimeException("货品下边必须绑定供应商！，请绑定供应商");
            }
        }
        //处理配件情况
            map.remove("gys");
            if(map.containsKey("pj")){
                List<Map<String,Object>> array= JSONArray.fromObject(map.get("pj"));
                for(Map<String,Object> map1:array){map1.put("ckid",ckid);}
                if(array.size()>0){
                    //删除原有的货品配件后添加进新编辑的配件
                    int del=wmsGoodsAccessoriesService.baseDeleteBySshpid(map.get("id").toString());
                        wmsGoodsAccessoriesService.baseInsertByMap(array,map.get("id").toString());

                }

            }
            //修改货品
            WmsGoods goods = new WmsGoods();
            goods.setId(map.get("id").toString());
            if (map.containsKey("bh")) goods.setBh(map.get("bh").toString());
            if (map.containsKey("mc")) goods.setMc(map.get("mc").toString());
            if (map.containsKey("zlid")) goods.setZlid(map.get("zlid").toString());
            if (map.containsKey("tm")) goods.setTm(map.get("tm").toString());
            if (map.containsKey("bkxs")) goods.setBkxs(map.get("bkxs").toString());
            if (map.containsKey("cjsn")) goods.setCjsn(map.get("cjsn").toString());
            if (map.containsKey("sfyx")) goods.setSfyx(map.get("sfyx").toString());
            if (map.containsKey("zhhp")) goods.setZhhp(map.get("zhhp").toString());
            if (map.containsKey("kczdl")) goods.setKczdl(map.get("kczdl").toString());
            if (map.containsKey("kczxl")) goods.setKczxl(map.get("kczxl").toString());
            if (map.containsKey("yxq")) goods.setYxq(map.get("yxq").toString());
            if (map.containsKey("zqlx")) goods.setZqlx(map.get("zqlx").toString());
            if (map.containsKey("yxqkz")) goods.setYxqkz(map.get("yxqkz").toString());
            if (map.containsKey("sxqyj")) goods.setSxqyj(map.get("sxqyj").toString());
            if (map.containsKey("jhwzlx")) goods.setJhwzlx(map.get("jhwzlx").toString());
            if (map.containsKey("jhwnlx")) goods.setJhwnlx(map.get("jhwnlx").toString());
            if (map.containsKey("jhxnlx")) goods.setJhxnlx(map.get("jhxnlx").toString());
            if (map.containsKey("jhtnlx")) goods.setJhtnlx(map.get("jhtnlx").toString());
            if (map.containsKey("bhsx")) goods.setBhsx(map.get("bhsx").toString());
            if (map.containsKey("bhdw")) goods.setBhdw(map.get("bhdw").toString());
            if (map.containsKey("ccqbh")) goods.setCcqbh(map.get("ccqbh").toString());
            if (map.containsKey("xjhwbh")) goods.setXjhwbh(map.get("xjhwbh").toString());
            if(map.containsKey("qzfs")) goods.setQzfs(map.get("qzfs").toString());
            if(map.containsKey("zjgzid")){ goods.setZjgzid(map.get("zjgzid").toString());}else {goods.setZjgzid("0");}
            if(map.containsKey("bom")){goods.setBom(map.get("bom").toString());}else{goods.setBom("0");}
        if(map.containsKey("nc")){goods.setNc(map.get("nc").toString());}else{goods.setNc("");}
        if(map.containsKey("gg")){goods.setGg(map.get("gg").toString());}else{goods.setGg("");}
            goods.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            goods.setCkid(ckid);
           dao.baseUpdateByPrimaryKeySelective(goods);

            if(map.containsKey("jhwzlx")){
                WmsOneLevelPickingLocation oneLocation=new WmsOneLevelPickingLocation();
                if("0".equals(map.get("jhwzlx").toString())){
                    if(map.containsKey("zkwid")){oneLocation.setKwid(map.get("zkwid").toString());}else {oneLocation.setKwid("");}
                }else{
                    if(map.containsKey("zkwid")){oneLocation.setKwid(map.get("zkwid").toString());}else{
                        throw new RuntimeException("库位类型不是存储库位必须选择库位");
                    }
                }

                if(map.containsKey("id"))oneLocation.setSshpid(map.get("id").toString());
                oneLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                oneLocation.setKwlx(map.get("jhwzlx").toString());
                oneLocation.setCkid(ckid);
               wmsOneLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(oneLocation);
            }

            if(map.containsKey("jhwnlx")){
                WmsTwoLevelPickingLocation twoLocation=new WmsTwoLevelPickingLocation();
                if("0".equals(map.get("jhwnlx").toString())){
                    if(map.containsKey("nkwid")){twoLocation.setKwid(map.get("nkwid").toString());}else {twoLocation.setKwid("");}
                }else{
                    if(map.containsKey("nkwid")){twoLocation.setKwid(map.get("nkwid").toString());}else{
                        throw new RuntimeException("库位类型不是存储库位必须选择库位");
                    }
                }
                if(map.containsKey("id"))twoLocation.setSshpid(map.get("id").toString());
                twoLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                twoLocation.setKwlx(map.get("jhwnlx").toString());
                twoLocation.setCkid(ckid);
               wmsTwoLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(twoLocation);
            }
            if(map.containsKey("jhxnlx")){
                WmsThreeLevelPickingLocation threeLocation=new WmsThreeLevelPickingLocation();
                if("0".equals(map.get("jhxnlx").toString())){
                    if(map.containsKey("xkwid")){threeLocation.setKwid(map.get("xkwid").toString());}else{threeLocation.setKwid("");}
                }else{
                    if(map.containsKey("xkwid")){threeLocation.setKwid(map.get("xkwid").toString());}else{
                        throw new RuntimeException("库位类型不是存储库位必须选择库位");
                    }
                }

                if(map.containsKey("id"))threeLocation.setSshpid(map.get("id").toString());
                threeLocation.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                threeLocation.setKwlx(map.get("jhxnlx").toString());
                threeLocation.setCkid(ckid);
             wmsThreeLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(threeLocation);
            }

    }
   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsGoods entity){
         return dao.baseUpdateByPrimaryKey( entity );
    }
    public String setEntity(Map<String,Object> map,String key){
        if(map.containsKey(key)){
            return  map.get(key).toString();
        }else{
            return "";
        }
    }
    /**
     *修改 （匹配有值的字段）
     * @param id 主键ID列表

     * @return int
     */
    public WmsGoods baseSelectByBaseSelectByGoodsEdit(  String id){
        return dao.baseSelectByGoodsEdit(id);
    }
    //根据货品Id查询供应商优先级

    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询供应商优先级信息")
    public List<WmsGoodsSuppliers> selectSuppliersByHpid(String hpid) throws ServiceException{
        try {
            //获取货品id 查询供应商情况
            return wmsGoodsSuppliersService.baseSelectBySshpid(hpid);
        }catch (Exception e){
            throw new ServiceException("查询供应商优先级信息");
        }

    }
    //根据货品查询配件信息
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询货品配件信息")
    public List<WmsGoodsAccessories> selectAccessoriesByHpid(String hpid) throws ServiceException{
        try {
            //获取货品id 查询供配件
            return wmsGoodsAccessoriesService.baseSelectBySshpid(hpid);
        }catch (Exception e){
            throw new ServiceException("查询货品配件信息");
        }

}
    /**
     * 查询（根据货主ID查询货主对应的货品）
     * @param sshzid 货主ID
     * @param mc 货品名称
     * @return User
     */
    public List<WmsGoods>  baseSelectGoodsBySshzid(String sshzid,String mc,String hpid,String bh){
        return dao.baseSelectGoodsBySshzid(sshzid,mc,hpid,bh);
    }
    /**
     *货品编号查重 （匹配有值的字段）
     * @param bh 货品编号
     * @return
     */
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "货品编号去重")
    public Integer baseSelectGoodsBh(String bh,String id) {
        return dao.baseSelectGoodsBh(bh,id);
    }
    /**
     *随机生成货品编号 （匹配有值的字段）
     * @return
     */
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "货品编号最大值用于新增编号")
    public String baseSelectGoodsBhMax()throws ServiceException{
       String bhf=dao.baseSelectGoodsBhMax();
       if(bhf!=null){
           Long  v=Long.valueOf(bhf);
           bhf=String.valueOf(v+1);
       }else{
           bhf="10000000001";
       }
       if(bhf==null){
           throw new ServiceException("获取编号失败");
       }else{
           return bhf;
       }
    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询库位组信息")
    public List<WmsLibrarypositiongroup> seachLibrarypositiongroup(String sshzid,String ckid,String mc) {
        return dao.seachLibrarypositiongroup(sshzid, ckid,mc);
    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "添加库位组绑定货品信息")
    @Transactional
    public void addLibrarypositiongroupBindingGoods(List<String> ids,String hpid,String sshzid,String ckid) throws SucessException,ServiceException{
           WmsGoodsLocation goods=null;
        String max=wmsGoodsLocationMapper.seackMaxPxByHpid(hpid);
        int px=1;
        if(max!=null){
            px=Integer.parseInt(max)+1;
        }
        for(String id:ids){
            goods=new WmsGoodsLocation();
           WmsLibrarypositiongroup group= dao.selectByGroupId(id);
            goods.setId(UUIDUtils.uuid());
            goods.setKwzid(id);
            goods.setHpid(hpid);
            goods.setPx(px);
            goods.setHzid(sshzid);
            goods.setCkid(ckid);
            goods.setKwzmc(group.getMc());
            int status=wmsGoodsLocationMapper.baseInsertSelective(goods);

            px++;
           }

    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询货品绑定库位组信息")
    public List<WmsGoodsLocation> seachGoodsBindingLibrarypositiongroup(String hpid) {
        return wmsGoodsLocationMapper.baseSelectByHpid(hpid);
    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "删除货品绑定库位组")
    public void delectGoodsBindingLibrarypositiongroup(List<String> ids)throws ServiceException,SucessException {
        System.out.println(ids);
        Integer status= wmsGoodsLocationMapper.baseDeleteBathPrimaryKeys(ids);
        if(status==0){
            throw new ServiceException("删除货品绑定库位组失败");
        }
    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "更新货品库位组绑定序号")
    public void updateGoodsBindingLibrarypositiongroup(List<WmsGoodsLocation> locations)throws ServiceException,SucessException {
       for(WmsGoodsLocation location:locations) {
           Integer status = wmsGoodsLocationMapper.baseUpdateByPrimaryKeySelective(location);
           if (status == 0) {
               throw new ServiceException("更新货品库位组绑定序号失败");
           }
       }
    }
    //根据货品查询配件信息
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询货主信息")
    public WmsOwner seachOwnerXx(String hzid,String ckid) throws ServiceException{
        try {
            //获取货品id 查询供配件
            return dao.seachOwnerXx(hzid,ckid);
        }catch (Exception e){
            throw new ServiceException("查询或注信息失败");
        }

    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "查询库位类型信息")
    public List<SysDictionary> seachKwlx(String lx) throws ServiceException{
        try {
            return dao.seachKwlx(lx);
        }catch (Exception e){
            throw new ServiceException("查询或注信息失败");
        }

    }
    @BaseServiceDescribe(moduleName = "货品管理",btnName = "解除绑定库位")
    public void cleanLibraryposition(String hpid,String lx,String kwid) throws ServiceException {

        if ("jhwzlx".equals(lx)) {
            //主单位
            List<WmsOneLevelPickingLocation> ones = wmsOneLevelPickingLocationMapper.baseSelectBySshpid(hpid);
            if (ones.size() > 0) {
                throw new ServiceException("原拣货位有待处理库存，请处理好在调整");
            } else {
                WmsOneLevelPickingLocation location = wmsOneLevelPickingLocationMapper.baseSelectKwidBySshpid(hpid);//查询货品绑定的库位Id
                updateKwid(location.getKwid(),hpid,kwid);//修改库存
                WmsOneLevelPickingLocation one = new WmsOneLevelPickingLocation();
                one.setSshpid(hpid);
                one.setKwid(kwid);
                wmsOneLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(one);//修改货品绑定库位
            }
        } else if ("jhwnlx".equals(lx)) {
            //内包装
            List<WmsTwoLevelPickingLocation> twos = wmsTwoLevelPickingLocationMapper.baseSelectBySshpid(hpid);
            if (twos.size() > 0) {
                throw new ServiceException("原拣货位有待处理库存，请处理好在调整");
            } else {
                WmsTwoLevelPickingLocation location = wmsTwoLevelPickingLocationMapper.baseSelectKwidBySshpid(hpid);//查询货品绑定的库位ID
                updateKwid(location.getKwid(),hpid,kwid);
                WmsTwoLevelPickingLocation two = new WmsTwoLevelPickingLocation();
                two.setSshpid(hpid);
                two.setKwid(kwid);
                wmsTwoLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(two);//修改货品绑定库位
            }

        } else if ("jhxnlx".equals(lx)) {
            //箱包装
            List<WmsThreeLevelPickingLocation> threes = wmsThreeLevelPickingLocationMapper.baseSelectBySshpid(hpid);
            if (threes.size() > 0) {
                throw new ServiceException("原拣货位有待处理库存，请处理好在调整");
            } else {
                WmsThreeLevelPickingLocation location = wmsThreeLevelPickingLocationMapper.baseSelectKwidBySshpid(hpid);//查询货品绑定的库位id
                updateKwid(location.getKwid(),hpid,kwid);
                WmsThreeLevelPickingLocation three = new WmsThreeLevelPickingLocation();
                three.setSshpid(hpid);
                three.setKwid(kwid);
                wmsThreeLevelPickingLocationMapper.baseUpdateByPrimaryKeySelective(three);//修改货品绑定库位
            }
        }
    }
        public void updateKwid(String ykwid,String hpid,String xkwid){
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<WmsStock> stocks=wmsStockMapper.seachHpkc(ykwid,hpid);//查询要修改的库存
            WmsStock stock=null;
            for(WmsStock s:stocks){
                stock=new WmsStock();
                stock.setId(s.getId());
                stock.setKwid(xkwid);
                stock.setYdsj(format.format(new Date()));
                wmsStockMapper.baseUpdateByPrimaryKeySelective(stock);
            }
    }
    @BaseServiceDescribe(moduleName = "货品管理", btnName = "导入货品信息")
    public void importGoodsExcle(HttpSession session, String  filepath)throws Exception,ServiceException{
        ImportParams params = new ImportParams();
        params.setNeedSave(false);
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setDataHanlder(new GoodsMapImportHanlder());
        JSONObject jb = JSONObject.fromObject(filepath);
        URL url = new URL((String) jb.get("filepath"));
        URLConnection conn = url.openConnection();
        List<Map<String, Object>> result = ExcelImportUtil.importExcel(
               conn.getInputStream(),
                Map.class, params);
        System.out.println("result:"+result);
        UserInfo userinfo = (UserInfo) session.getAttribute(SessionInfo.USER_INFO);
        List<SysHz> hz = (List<SysHz>) session.getAttribute(BaseSessionInfo.SessionConsignor);
        //仓库id
        String ckid = String.valueOf(userinfo.getUser().getOrgId().get(0));
        //货主id
        String hzid = null;
        if (hz.size() > 0) {
            hzid = hz.get(0).getHzid();
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < result.size(); i++) {
            result.get(i).put("num", i + 2);
        }
        //表格内去重
        removeDuplicate(result);
        //数据库去重
        removeDateDuplicate(result);
        //添加数据
        for(int i=0;i<result.size();i++){
            result.get(i).put("hzid",hzid);//放入货主id
            result.get(i).put("ckid",ckid);//放入仓库id
            //新增货品
            Integer bh=dao.seachHpCz(result.get(i).get("bh").toString());
            if(bh==0){
                //新增货品中的所有信息
                addGoods(result.get(i));
            }
        }
    }
    /**
     * 新增货品
     */
    public void addGoods(Map<String,Object> map)throws ServiceException{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        WmsGoods goods = new WmsGoods();
        //基础信息
        goods.setId(UUIDUtils.uuid());
        if (map.containsKey("bh")&&!"".equals(map.get("bh").toString())) goods.setBh(map.get("bh").toString());
        if (map.containsKey("mc")&&!"".equals(map.get("mc").toString())) goods.setMc(map.get("mc").toString());
        if(!"".equals(map.get("zlmc").toString())){
            WmsGoodsType type=dao.seachHpid(map.get("zlmc").toString());
            goods.setZlid(type.getId());
        }else{
            throw new RuntimeException(map.get("bh").toString()+"此货品必须填写所属种类");
        }
        if (map.containsKey("tm")) goods.setTm(map.get("tm").toString());
        if(!"".equals(map.get("bzmc").toString())){
            WmsPacking packing=dao.seachBzid(map.get("bzmc").toString());
            if(packing!=null) {
                goods.setBzid(packing.getId());
                WmsPacking pa = new WmsPacking();
                pa.setId(packing.getId());
                pa.setFphpid(goods.getId());
                wmsPackingService.baseUpdateByPrimaryKeySelective(pa);
            }else{
                throw new RuntimeException(map.get("bh").toString()+"包装必须未绑定过货品");
            }
        }else{
            throw new RuntimeException(map.get("bh").toString()+"此货品必须保定包装");
        }

        if (map.containsKey("bhsx")) goods.setBhsx(map.get("bhsx").toString());
        if("是".equals(map.get("bkxs").toString())){
            goods.setBkxs("1");
        }else{
            goods.setBkxs("0");
        }
        if("是".equals(map.get("cjsn").toString())){
            goods.setCjsn("1");
        }else{
            goods.setCjsn("0");
        }

        goods.setSfyx("1");

        if("是".equals(map.get("ccqbh").toString())){
            goods.setCcqbh("1");
        }else{
            goods.setCcqbh("0");
        }
        if(map.containsKey("nc")){goods.setNc(map.get("nc").toString());}else{goods.setNc("");}
        if(map.containsKey("gg")){goods.setGg(map.get("gg").toString());}else{goods.setGg("");}
        //货品配件
        if("是".equals(map.get("zhhp").toString())){
            goods.setZhhp("1");
            if(!"".equals(map.get("pjhpbh").toString())){
                WmsGoodsAccessories pj=new WmsGoodsAccessories();
                pj.setId(UUIDUtils.uuid());
                pj.setSshpid(goods.getId());
               WmsGoods g= dao.seachHpidBybh(goods.getBh());
                pj.setHpid(goods.getId());
                pj.setSl(map.get("pjhpsl").toString());
                pj.setCkid(map.get("ckid").toString());
                wmsGoodsAccessoriesService.baseInsertSelective(pj);
            }

        }else{
            goods.setZhhp("0");
        }
        if (map.containsKey("kczdl")) goods.setKczdl(map.get("kczdl").toString());
        if (map.containsKey("kczxl")) goods.setKczxl(map.get("kczxl").toString());
        if("取整补货".equals(map.get("bhdw").toString())){
            goods.setBhdw("1");
            if("向上取整".equals(map.get("qzfs").toString())){
                goods.setQzfs("1");
            }else if("向下取整".equals(map.get("qzfs").toString())){
                goods.setQzfs("2");
            }else {
                goods.setQzfs("0");
            }
        }else{
            goods.setBhdw("0");
        }
        if("是".equals(map.get("xjhwbh").toString())){
            goods.setXjhwbh("1");
        }else{
            goods.setXjhwbh("0");
        }

        //有效期控制
        if("是".equals(map.get("yxqkz").toString())){
            goods.setYxqkz("1");
            if("生产日期".equals(map.get("zqlx").toString())){
                goods.setZqlx("0");
            }else if("入库日期".equals(map.get("zqlx").toString())){
                goods.setZqlx("1");
            }
            if (map.containsKey("yxq")){ goods.setYxq(map.get("yxq").toString());}else{goods.setYxq("");};
            if (map.containsKey("sxqyj")){ goods.setSxqyj(map.get("sxqyj").toString());}else{goods.setSxqyj("");}
        }else{
            goods.setYxqkz("0");
        }
        if("存在".equals(map.get("bom").toString())){
            goods.setBom("1");
            WmsGoodsBom bom=new WmsGoodsBom();
            bom.setId(UUIDUtils.uuid());
            bom.setSshpid(goods.getId());
            WmsGoods g= dao.seachHpidBybh(goods.getBh());
            bom.setHpid(g.getId());
            bom.setSl(Double.parseDouble(map.get("wlhpsl").toString()));
            wmsGoodsBomMapper.baseInsert(bom);
        }else {
            goods.setBom("0");
        }
        //主单位库为类型绑定
        if(!"".equals(map.get("jhwzlx").toString())) {
            WmsOneLevelPickingLocation one = new WmsOneLevelPickingLocation();
            one.setId(UUIDUtils.uuid());
            one.setSshpid(goods.getId());
            one.setGxsj(df.format(new Date()));
            one.setCkid(map.get("ckid").toString());
            if(!"".equals(map.get("zkwmc").toString())){
                WmsLibraryPosition lp=dao.seachKwidBymc(map.get("zkwmc").toString());
                one.setKwid(lp.getId());
                one.setKwlx(lp.getLx());
                goods.setJhwzlx(lp.getLx());
            }else{
                one.setKwid("");
                one.setKwlx("0");
                goods.setJhwzlx("0");
            }
            wmsOneLevelPickingLocationMapper.baseInsert(one);
        }
        //内包装库为类型绑定
        if(!"".equals(map.get("jhwnlx").toString())) {
            WmsTwoLevelPickingLocation two = new WmsTwoLevelPickingLocation();
            two.setId(UUIDUtils.uuid());
            two.setSshpid(goods.getId());
            two.setGxsj(df.format(new Date()));
            two.setCkid(map.get("ckid").toString());
            if(!"".equals(map.get("nkwmc").toString())){
                WmsLibraryPosition lp=dao.seachKwidBymc(map.get("nkwmc").toString());
                two.setKwid(lp.getId());
                two.setKwlx(lp.getLx());
                goods.setJhwnlx(lp.getLx());
            }else{
                two.setKwid("");
                two.setKwlx("0");
                goods.setJhwnlx("0");
            }
            wmsTwoLevelPickingLocationMapper.baseInsert(two);
        }
        //箱包装库为类型绑定
        if(!"".equals(map.get("jhxnlx").toString())) {
            WmsThreeLevelPickingLocation three = new WmsThreeLevelPickingLocation();
            three.setId(UUIDUtils.uuid());
            three.setSshpid(goods.getId());
            three.setGxsj(df.format(new Date()));
            three.setCkid(map.get("ckid").toString());
            if(!"".equals(map.get("xkwmc").toString())){
                WmsLibraryPosition lp=dao.seachKwidBymc(map.get("xkwmc").toString());
                three.setKwid(lp.getId());
                three.setKwlx(lp.getLx());
                goods.setJhxnlx(lp.getLx());
            }else{
                three.setKwid("");
                three.setKwlx("0");
                goods.setJhxnlx("0");
            }
            wmsThreeLevelPickingLocationMapper.baseInsert(three);
        }
        //质检规则
        if(!"".equals(map.get("zjgzmc").toString())) {
            WmsQualityTesting testing = dao.seachzjgzidBymc(map.get("zjgzmc").toString());
            goods.setZjgzid(testing.getId());
        }else {
            goods.setZjgzid("0");
        }

//        if(!"".equals(map.get("kwzmc").toString())){
//            WmsLibrarypositiongroup group=dao.seachKwzidBymc(map.get("kwzmc").toString());
//            WmsGoodsLocation gl=new WmsGoodsLocation();
//            gl.setId(UUIDUtils.uuid());
//            gl.setKwzmc(map.get("kwzmc").toString());
//            gl.setKwzid(group.getId());
//            gl.setCkid(map.get("ckid").toString());
//            gl.setHzid(map.get("hzid").toString());
//            gl.setHpid(goods.getId());
//            Integer px=Integer.parseInt(wmsGoodsLocationMapper.seackMaxPxByHpid(map.get("id").toString()));
//            gl.setPx(px+1);
//            wmsGoodsLocationMapper.baseInsert(gl);
//        }
        if(!"".equals(map.get("gysbh").toString())){
            WmsOwnerSupplier su=dao.seachGysidByBh(map.get("gysbh").toString());
            WmsGoodsSuppliers gs=new WmsGoodsSuppliers();
            gs.setId(UUIDUtils.uuid());
            gs.setCkid(map.get("ckid").toString());
            gs.setGysid(su.getId());
            gs.setSfyx("1");
            gs.setSshpid(goods.getId());
            gs.setYxj(map.get("gysyxj").toString());
            wmsGoodsSuppliersService.baseInsertSelective(gs);
        }else{
            throw new RuntimeException("货品必须绑定供应商信息");
        }
        goods.setGxsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        goods.setCkid(map.get("ckid").toString());
        dao.baseInsertSelective(goods);
    }
    /**
     * 数据库去重
     */
    public void removeDateDuplicate(List<Map<String, Object>> lis) throws ServiceException {
        StringBuffer sb = new StringBuffer();
        for(int i=0;i<lis.size();i++){
            Integer f=dao.baseSelectGoodsBh(lis.get(i).get("bh").toString(),"");
            if(f>0){
                sb.append("第"+lis.get(i).get("num")+"行，货品编号"+lis.get(i).get("bh")+",");
            }
            Integer count=dao.seachBzBdqk(lis.get(i).get("bzmc").toString());
            if(count!=1){
                sb.append("第"+lis.get(i).get("num")+"行，货品编号"+lis.get(i).get("bh")+"包装名称："+lis.get(i).get("bzmc")+",");
            }
            if(!"".equals(lis.get(i).get("zkwmc").toString())) {
                Integer zkw = dao.seachKwmc(lis.get(i).get("zkwmc").toString());
                if(zkw!=1){
                    sb.append("第"+lis.get(i).get("num")+"行，货品编号"+lis.get(i).get("bh")+"主单位拣货位名称："+lis.get(i).get("zkwmc")+"不存在,");
                }
            }
            if(!"".equals(lis.get(i).get("zjgzmc").toString())){
                Integer zjgz=dao.countZjgzmc(lis.get(i).get("zjgzmc").toString());
                if(zjgz!=1) {
                    sb.append("第" + lis.get(i).get("num") + "行，货品编号" + lis.get(i).get("bh") + "质检规则：" + lis.get(i).get("zjgzmc") + ",");
                }
            }
            if(!"".equals(lis.get(i).get("nkwmc").toString())) {
                Integer nkw = dao.seachKwmc(lis.get(i).get("nkwmc").toString());
                if(nkw!=1){
                    sb.append("第"+lis.get(i).get("num")+"行，货品编号"+lis.get(i).get("bh")+"，内包装拣货位名称："+lis.get(i).get("nkwmc")+"不存在，");
                }
            }
            if(!"".equals(lis.get(i).get("xkwmc").toString())) {
                Integer xkw = dao.seachKwmc(lis.get(i).get("xkwmc").toString());
                if (xkw != 1) {
                    sb.append("第" + lis.get(i).get("num") + "行，货品编号" + lis.get(i).get("bh") + ",箱包装拣货位名称：" + lis.get(i).get("xkwmc") + "不存在，");
                }
            }
            Integer zl=dao.seachHpzl(lis.get(i).get("zlmc").toString());
            if(zl!=1){
                sb.append("第"+lis.get(i).get("num")+"行，货品编号"+lis.get(i).get("bh")+"种类名称："+lis.get(i).get("zlmc")+",");
            }
            if(!"".equals(lis.get(i).get("wlhpbh").toString())) {
                Integer bh = dao.seachHpCz(lis.get(i).get("wlhpbh").toString());
                if (bh != 1) {
                    sb.append("第" + lis.get(i).get("num") + "行，货品编号" + lis.get(i).get("bh") + "物料货品编号：" + lis.get(i).get("wlhpbh") + "不存在，");
                }
            }
            if(!"".equals(lis.get(i).get("pjhpbh").toString())) {
                Integer bh2 = dao.seachHpCz(lis.get(i).get("pjhpbh").toString());
                if (bh2 != 1) {
                    sb.append("第" + lis.get(i).get("num") + "行，货品编号" + lis.get(i).get("bh") + "物料货品编号：" + lis.get(i).get("wlhpbh") +"不存在，");
                }
            }

            if (sb != null && !"".equals(sb) && sb.length() > 0) {
                throw new ServiceException("表格中" + sb + "货品编号重复或包装已被占用，导入失败");
            }
        }
    }
    /**
     * 表格内去重
     */
    public void removeDuplicate(List<Map<String, Object>> lis) throws ServiceException {
        //报表内不允许存在相同货品添加多次的情况
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lis.size() - 1; i++) {
            for (int j = i + 1; j < lis.size(); j++) {
                //JSONObject jb = new JSONObject();
                if (lis.get(j).get("bh").equals(lis.get(i).get("bh")) && lis.get(j).get("pjhpbh").equals(lis.get(i).get("pjhpbh"))&& lis.get(j).get("pjhpbh").equals(lis.get(i).get("pjhpbh"))&& lis.get(j).get("gysbh").equals(lis.get(i).get("gysbh"))&&lis.get(j).get("kwzmc").equals(lis.get(i).get("kwzmc"))){
                    sb.append("第" + lis.get(j).get("num") + "行，货品编号:" + lis.get(j).get("hpbh") + ",");
                    lis.remove(j);
                    j--;
                }
            }
        }
        if (sb != null && !"".equals(sb) && sb.length() > 0) {
            throw new ServiceException("表格中" + sb + "货品重复，导入失败");
        }

    }
}
